package filter

import (
	"gitee.com/kristas/booting-go/framework"
	"gitee.com/kristas/booting-go/framework/core/statement/types"
	"gitee.com/kristas/booting-go/framework/web"
	"net/http"
)

func init() {
	framework.Component(new(CorsFilter))
}

type CorsFilter struct {
	types.Filter `order:"99" pattern:"/*"`
}

func (c *CorsFilter) DoFilter(w http.ResponseWriter, r *http.Request, chain web.FilterChain) error {
	err := chain.DoFilter(w, r)
	w.Header().Set("Access-Control-Allow-Origin", "*")
	if r.Method == "OPTIONS" {
		w.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,PATCH,OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization")
		w.WriteHeader(http.StatusNoContent)
	}
	return err
}
